import { watch, unref } from 'vue'
/**
 * Get the dom element of a ref of element or Vue component instance
 *
 * @param elRef
 */
function unrefElement (elRef) {
  var _a, _b
  const plain = unref(elRef)
  // eslint-disable-next-line no-void
  return (_b = (_a = plain) === null || _a === void 0 ? void 0 : _a.$el) !== null && _b !== void 0 ? _b : plain
}
export function ob (target, cb) {
  let cleanup
  const stopWatch = watch(() => ({
    el: unrefElement(target)
  }), ({ el }) => {
    if (!el) return
    const observer = new window.IntersectionObserver(cb, {
      root: null,
      rootMargin: '0px',
      threshold: 0.1
    })
    observer.observe(el)
    cleanup = () => {
      observer.disconnect()
      cleanup = null
    }
  }, { immediate: true, flush: 'post' })

  const stop = () => {
    cleanup()
    stopWatch()
  }

  return { stop }
}
